package com.example.rxtxdemo.js;

import com.fazecast.jSerialComm.*;

public class SerialPortManager {
    private SerialPort mSerialPort;

    public SerialPortManager() {
        mSerialPort = null;
    }

    public void init(String portName) {
        mSerialPort = SerialPort.getCommPort(portName);
        mSerialPort.openPort();
        mSerialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
        mSerialPort.setComPortParameters(38400, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
        mSerialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 1000, 1000);
    }

    public void close() {
        if (mSerialPort != null && mSerialPort.isOpen()) {
            mSerialPort.closePort();
        }
    }

    private int write(byte[] data) {
        if (mSerialPort == null || !mSerialPort.isOpen()) {
            return 0;
        }
        return mSerialPort.writeBytes(data, data.length);
    }

    private int read(byte[] data) {
        if (mSerialPort == null || !mSerialPort.isOpen()) {
            return 0;
        }
        return mSerialPort.readBytes(data, data.length);
    }

    public int readWriteTest(String portName) {
        init(portName);
        byte[] order = {(byte) 0xA5, (byte) 0x5A, (byte) 0x02, (byte) 0x00, (byte) 0xFD};
        write(order);
        byte[] data = new byte[100];
        try {
            int i = 0;
            while (mSerialPort.bytesAvailable() < 6 && i++ < 100)
                Thread.sleep(20);
        } catch (Exception e) {
        }

        int len = read(data);
        if (data == null) {
            close();
            return -1;
        }
        System.out.println(len);
        for (int i = 0; i < len; i++) {
            System.out.format("%x ", data[i]);
        }
        close();
        return 0;
    }


    public static void main(String[] args) {
        SerialPortManager sm = new SerialPortManager();
        sm.readWriteTest("ttyTHS0");
    }
}